package com.baidu.iit.pxp.behavior;

import com.baidu.iit.pvm.PvmActivity;
import com.baidu.iit.pvm.PvmTransition;
import com.baidu.iit.pvm.delegate.ActivityExecution;
import com.baidu.iit.pxp.handler.GatewayActivityBehavior;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * User: huangweili
 * Date: 14-4-27
 * Time: 上午9:19
 */
public class ParallelGatewayActivityBehavior extends GatewayActivityBehavior {

    private static Logger log = LoggerFactory.getLogger(ParallelGatewayActivityBehavior.class);

    public void execute(ActivityExecution execution) throws Exception {

        PvmActivity activity = execution.getActivity();
        List<PvmTransition> outgoingTransitions = execution.getActivity().getOutgoingTransitions();

        execution.inactivate();
        lockConcurrentRoot(execution);

        List<ActivityExecution> joinedExecutions = execution.findInactiveConcurrentExecutions(activity);
        int nbrOfExecutionsToJoin = execution.getActivity().getIncomingTransitions().size();
        int nbrOfExecutionsJoined = joinedExecutions.size();
        if (nbrOfExecutionsJoined==nbrOfExecutionsToJoin) {

            if(log.isDebugEnabled()) {
                log.debug("parallel gateway '{}' activates: {} of {} joined", activity.getId(), nbrOfExecutionsJoined, nbrOfExecutionsToJoin);
            }
            execution.takeAll(outgoingTransitions, joinedExecutions);

        } else if (log.isDebugEnabled()){
            log.debug("parallel gateway '{}' does not activate: {} of {} joined", activity.getId(), nbrOfExecutionsJoined, nbrOfExecutionsToJoin);
        }
    }

}
